﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Text;
using System.Web.SessionState;

namespace WebCache
{
    public class SessionCache:BaseCache
    {
        private static Dictionary<string, object> dictCache = new Dictionary<string, object>();
        public override string[] Keys
        {
            get
            {
                HttpSessionState session = HttpContext.Current == null ? null : HttpContext.Current.Session;
                if (session != null)
                {
                    System.Collections.IEnumerator enumerator = session.Keys.GetEnumerator();
                    string[] keys = new string[session.Count];
                    int index = 0;
                    while (enumerator.MoveNext()) keys[index++] = enumerator.Current.ToString();
                    return keys;
                }
                else
                {
                    return dictCache.Keys.ToArray();
                }
            }
        }

        public override object this[string key]
        {
            get {
                HttpSessionState session = HttpContext.Current == null ? null : HttpContext.Current.Session;
                if (session != null) return session[key];
                else if (dictCache.ContainsKey(key)) return dictCache[key];
                return null;
            }
            set {
                HttpSessionState session = HttpContext.Current == null ? null : HttpContext.Current.Session;
                if (session != null) session[key] = value;
                else dictCache[key] = value;
            }
        }

        public override void Remove(string key)
        {
            HttpSessionState session = HttpContext.Current == null ? null : HttpContext.Current.Session;
            if (session != null) session.Remove(key);
            else if(dictCache.ContainsKey(key)) dictCache.Remove(key);
        }
    }
}
